package com.zlt.service.impl;

import com.zlt.dao.Impl.VipDaoImpl;
import com.zlt.dao.VipDao;
import com.zlt.dto.VipLogDTO;
import com.zlt.entity.*;
import com.zlt.service.VipService;
import com.zlt.util.SqlUtil;
import com.zlt.util.TimeUtil;
import com.zlt.vo.JobVo;
import com.zlt.vo.UserVipVO;
import com.zlt.vo.VipLogVO;
import com.zlt.vo.VipVO;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

public class VipServiceImpl implements VipService {


    VipDao  vipDao = new VipDaoImpl();
    @Override
    public List<VipVO> selectVipAllType() {


       List<Vip> vips = vipDao.selectVipAllType();

       List<VipVO> vipVOS = new ArrayList<>();

       if (vips!=null && !vips.isEmpty()){




           vips.forEach(v->{
               VipVO vipVO = new VipVO();
               try {
                   BeanUtils.copyProperties(vipVO,v);
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               } catch (InvocationTargetException e) {
                   e.printStackTrace();
               }
               vipVOS.add(vipVO);

           });


       }


        return vipVOS;
    }






    //这里要进行事务管理  一个方法中有多个操作数据库的sql语句
    @Override
    public boolean charge(VipLogDTO vipLogDTO) {
        //用户进行充值

        //先判断用户是否登录  未登录不能充值


        //用户登录后  查询用户是否已经是会员 并且没有过期  0 代表没有过期

        UserVip userVip = vipDao.selectUserVip(vipLogDTO.getUid(),0);

        //说明用户已经是vip了并且没有过期
        if (userVip!=null){ //这个只能说明之前没有过期 还要重新验证一遍

            try {
                boolean notExpired = TimeUtil.isNotExpired(userVip.getEndTime());

                if (!notExpired){
                    int i = vipDao.updateVipExpired(vipLogDTO.getUid(),0);
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

        }


        userVip = vipDao.selectUserVip(vipLogDTO.getUid(),0);



        //查询招聘者充值的vip等级
        Vip vip = vipDao.selectVipType(vipLogDTO.getVid());


        ///////////////////////获取最新的vip状态
        if (userVip!=null){ //如果用户之前就是vip  那么就续期

            String newEndTime = TimeUtil.addEndTime(userVip.getEndTime(), vip);

            userVip.setEndTime(newEndTime);

            int i = vipDao.delayVip(userVip);

            return i>0;



        }

        //如果用户是第一次充值  或者之前的vip已经过期  就重新创建一条记录


        userVip = new UserVip();

        userVip.setStartTime(TimeUtil.getCurrentDateString());
        userVip.setEndTime(TimeUtil.endTime(userVip,vip));
        userVip.setVid(vip.getVid());
        userVip.setUid(vipLogDTO.getUid());
        userVip.setState(0);

        int result = vipDao.createUserVip(userVip);


        return result>0;



    }




    @Override
    public int insertChargeLog(VipLogDTO vipLogDTO) {


        VipLog vipLog = new VipLog();

        try {
            BeanUtils.copyProperties(vipLog,vipLogDTO);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        System.out.println("vipLog:"+vipLog);

        int i = vipDao.insertChargeLog(vipLog);


        return 0;
    }

    @Override
    public Vip selectVipType(Integer vid) {


        Vip vip = vipDao.selectVipType(vid);


        return vip;
    }

    @Override
    public UserVipVO selectVipState(String uid) {

        //先查询这个用户之前是不是vip并且没有过期
        UserVip userVip = vipDao.selectUserVip(uid,0);


        //如果不为空 说明用户之前是vip    更新用户当前的vip状态
        if (userVip!=null){


            try {
                //vip是否过期  是与当前的时间进行比较
                boolean notExpired = TimeUtil.isNotExpired(userVip.getEndTime());

                //如果过期了  就要更新当前用户的vip状态
                if (!notExpired){

                    vipDao.updateVipExpired(uid,1);

                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

        }


        //获取最新的vip状态

        userVip = vipDao.selectUserVip(uid,0);


        UserVipVO userVipVO = new UserVipVO();

        try {


            BeanUtils.copyProperties(userVipVO,userVip);



        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        return userVipVO;
    }



    @Override
    public List<JobVo> selectVipJobs() {

        //查询所有之前没有过期的vip企业

        List<UserVip> userVips = vipDao.selectAllUserVip(0);

        //遍历这些之前这些未过期的用户   更新他们当前的vip状态

        if (userVips!=null){

            for (UserVip userVip : userVips) {

                try {
                    boolean notExpired = TimeUtil.isNotExpired(userVip.getEndTime());


                    if (!notExpired){ //如果vip企业已经过期了  更新vip状态

                        vipDao.updateVipExpired(userVip.getUid(),1);

                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }


        }



        //获取最新的vip企业

        userVips = vipDao.selectAllUserVip(0);

        //根据vip企业用户 查询通过的公司

        List<Company> companies = new ArrayList<>();

        if (userVips!=null){

            userVips.forEach(u->{

                Company company = new Company();

                company =  vipDao.selectVipCompany(u.getUid());

                if (company!=null){
                    companies.add(company);
                }

            });

        }


        //根据公司查询岗位  每个公司显示一个岗位

        //根据公司查询每个公司的岗位

        List<Job> jobs =  new ArrayList<>();


        if (companies!=null && !companies.isEmpty()){

            companies.forEach(c->{

                //把所有未下架的岗位查询出来   选中其中的几个岗位加入 jobs集合

                List<Job> tempJobs =  new ArrayList<>();

                tempJobs = vipDao.selectVipJobs(c.getCid(),0);





                if (tempJobs!=null && !tempJobs.isEmpty()){

                    //查询每个工作岗位的 岗位类型

                    for (Job tempJob : tempJobs) {


                    JobType jobType =  vipDao.selectJobType(tempJob.getJobType().getJtid());
                    tempJob.setJobType(jobType);


                    }



                    //一个公司 选择两个岗位（这里可以弄随机数也可以）
                    //或者将所有的未下架的岗位加入jobs  前端显示的时候 负责选择性渲染
                    tempJobs.get(0).setCompany(c);

                    jobs.add(tempJobs.get(0));
//                    jobs.add(tempJobs.get(1));

                }
            });
        }

        ////////////// //////////////////////////////////////////////////////////////////////////////
        //如果vip企业的岗位个数不够  那么我们就从非vip企业中选择岗位  加入到jobs中

        //查询所有通过的企业


        if (jobs==null ||jobs.size()<9){
            
            List<Company> allCompaniesList = vipDao.selectAllCompanys(0);

            if (allCompaniesList!=null && !allCompaniesList.isEmpty()){

                Company tempCompany = new Company();

                for (Company company : allCompaniesList) {

                    boolean flag=true;  //默认我们查询出来的企业都不是vip

                    for (Company c : companies) {

                        if (company.getCid()==c.getCid()){

                            //如果是vip  则将flag改为false
                            flag=false;
                            break;

                        }

                    }




                    if (flag){ //如果这个公司不是vip
                        //代码复用
                        List<Job> tempJobs =  new ArrayList<>();

                        tempJobs = vipDao.selectVipJobs(company.getCid(),0);




                        if (tempJobs!=null && !tempJobs.isEmpty()){

                            for (Job tempJob : tempJobs) {


                                JobType jobType =  vipDao.selectJobType(tempJob.getJobType().getJtid());
                                tempJob.setJobType(jobType);


                            }


                            //一个公司 选择两个岗位（这里可以弄随机数也可以）
                            //或者将所有的未下架的岗位加入jobs  前端显示的时候 负责选择性渲染
                            tempJobs.get(0).setCompany(company);
                            jobs.add(tempJobs.get(0));
//                            jobs.add(tempJobs.get(1));

                        }

                    }

                }

            }



        }
        /////////////////////////



        List<JobVo>  jobVos = new ArrayList<>();

        jobs.forEach(j->{
            JobVo jobVo = new JobVo();

            jobVos.add(jobVo);

            System.out.println(j);

            jobVo.setCname(j.getCompany().getCname());
            jobVo.setType(j.getJobType().getJtname());

            try {
                BeanUtils.copyProperties(jobVo,j);
                System.out.println(jobVo);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }

        });

        return jobVos;
    }

    @Override
    public List<JobVo> selectRecentJobs(int limit) {

        List<Job> jobs = vipDao.selectRecentJobs(limit);

        List<JobVo> jobVos =null;

       if (jobs!=null && !jobs.isEmpty()){


           for (Job job : jobs) {

               //查询当前工作属于哪一个公司

               if (job.getCompany().getCid()!=null){
                   Company company = vipDao.selectCompany(job.getCompany().getCid());

                   job.setCompany(company);

                   //查询当前工作所属的工作类型
                   JobType jobType =  vipDao.selectJobType(job.getJobType().getJtid());

                   job.setJobType(jobType);

               }



           }


           jobVos = new ArrayList<>();


           for (Job j : jobs) {

               System.out.println(j.getCompany().getCname());
               System.out.println(j.getJobType().getJtname());

               JobVo jobVo = new JobVo();

               jobVo.setCname(j.getCompany().getCname());
               jobVo.setType(j.getJobType().getJtname());
               System.out.println("j.getCompany().getCname():"+j.getCompany().getCname());
               System.out.println(".getJobType().getJtname():"+j.getJobType().getJtname());
               jobVos.add(jobVo);


               try {
                   BeanUtils.copyProperties(jobVo,j);
                   System.out.println(jobVo);
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               } catch (InvocationTargetException e) {
                   e.printStackTrace();
               }

           }


       }


        return jobVos;
    }

    @Override
    public List<VipLogVO> selectVipLogs(String uid) {

        List<VipLog> vipLogs = vipDao.selectVipLogs(uid);

        List<VipLogVO> vipLogVOS = new ArrayList<>();

        if (vipLogs!=null && !vipLogs.isEmpty()){


            for (VipLog vipLog : vipLogs) {


                VipLogVO vipLogVO = new VipLogVO();
                vipLogVOS.add(vipLogVO);

                try {
                    BeanUtils.copyProperties(vipLogVO,vipLog);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }


            }


        }


        return vipLogVOS;
    }

    @Override
    public int insertChargeRecord(VipLogDTO vipLogDTO) {

        int i =vipDao.insertChargeRecord(vipLogDTO);

        return i;
    }

    @Override
    public ChargeRecord selectChargeRecord(String out_trade_no) {

        String sql=  "select charge_record.crid, charge_record.uid, charge_record.money, charge_record.order_no, charge_record.state, charge_record.vid  \n" +
                "from  charge_record \n" +
                "where order_no=?";

        ChargeRecord chargeRecord = SqlUtil.selectOne(ChargeRecord.class, sql, out_trade_no);


        return chargeRecord;
    }


}
